package com.powernode.config.handler;

import com.alibaba.fastjson2.JSONObject;
import com.powernode.constant.AuthConstants;
import com.powernode.model.R;
import com.powernode.model.SecurityUser;
import com.powernode.util.JWTUtils;
import com.powernode.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;

/**
 * 登录成功处理器
 *  作用：生成令牌TOKEN
 */
@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从容器中获取Security安全认证用户信息
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 生成令牌TOKEN
        String jwt_token = JWTUtils.createJwt(JSONObject.toJSONString(securityUser));
        // 将令牌TOKEN存放到redis中(解决：token未过期问题)
        stringRedisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX +jwt_token,"", Duration.ofSeconds(AuthConstants.TOKEN_TIME));
        // 获取“记住我”状态
        Boolean rememberMe = Boolean.parseBoolean(request.getParameter("rememberMe"));
        if (rememberMe) {
            stringRedisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX +jwt_token,"", Duration.ofSeconds(AuthConstants.REMEMBER_ME_TOKEN_TIME));
        }


        // 响应结果
        ResponseUtils.write(response, R.OK(jwt_token));
    }
}
